<?php

//创建websocket服务器对象，监听0.0.0.0:9502端口
$ws = new Swoole\Websocket\Server("0.0.0.0", 9506);
$ws->set(array(
    'reactor_num'=>8,
    'worker_num' => 4,
    'backlog' => 128,
    'daemonize'=>1,
));
//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {

	$fd = $request->fd;
    echo "client-{$fd} is connect\n";
    //$ws->push($request->fd, "hello, welcome\n");
});

//监听WebSocket消息事件
$ws->on('message', function ($ws, $frame) {

    // $msg =  'from'.$frame->fd.":{$frame->data}\n";
	$data   = htmlentities(htmlspecialchars($frame->data));
    if(mb_strlen($data,'utf8')>30){
        $data = mb_substr($data, 0,30,'utf-8').'...';
    }

    // 正常发送
    $arr = array(
        'info'   => "$data",
        'img'    => '',
        'href'   => 'javascript:void(0);',
        'status' => 1
    );

    $msg = json_encode($arr);

    foreach($ws->connections as $fd) {
        $ws->push($fd, $msg);
    }

    
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();